from sim.genFragment import gen2
from sim.seamData import randomSeam2
from sim.rules import classify
from sim.config import loadConfig
import numpy as np
import pandas as pd
from npend import NpendWriter as NW
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一（替换sans-serif字体）
plt.rcParams['axes.unicode_minus'] = False
import random
# random.seed(1)

if __name__=="__main__":
    import matplotlib.pyplot as plt
    filePath = '../data/一号泵.csv'
    data = pd.read_csv(filePath, encoding="utf-8")
    fields=['出口压力', '进口压力', '瞬时流量']
    data = data[fields]
    fields.extend(['来水流量', '调水流量', '水罐液位'])
    dataPath='../data/dataTest.npd'
    labelPath='../data/labelTest.npd'
    dataWriter=NW(dataPath)
    labelWriter=NW(labelPath)
    count=0
    for i in range(2):
        seamData = randomSeam2(data.values, 500, [100, 200])
        num=seamData.shape[0]
        simData = gen2([456.0,617.1], [50,120], num)
        seamData=np.concatenate([seamData,simData.reshape((simData.shape[0],1))],axis=1)
        simData = gen2([456.0, 617.1], [50, 120], num)
        seamData = np.concatenate([seamData, simData.reshape((simData.shape[0],1))], axis=1)
        simData = gen2([5.0,10.5], [50, 120], num)
        seamData = np.concatenate([seamData, simData.reshape((simData.shape[0],1))], axis=1)

        df = pd.DataFrame(seamData, columns=fields)
        for field in fields:
            min = df[field].min()
            max = df[field].max()
            ran = max - min
            df[field] = df[field].map(lambda x: (x - min) / ran)
        df.plot()
        plt.show()
        plt.waitforbuttonpress()

        field2Idx={field:idx for idx,field in enumerate(fields)}
        T=30
        M=num-T
        config=loadConfig()
        thresh=config["thresh"]
        dataList=[]
        labelList=[]
        for i in range(M):
            sub=seamData[i:i+T,:]
            label,normData=classify(sub.copy(),field2Idx,thresh)
            if label is None:
                continue
            elif label!=0:
                dataList.append(normData)
                labelList.append(label)
            else:
                rand=np.random.random()
                if rand<0.1:
                    dataList.append(normData)
                    labelList.append(label)
        arrData=np.array(dataList,dtype="float32")
        arrLabel=np.array(labelList,dtype="int32")
        count+=len(arrLabel)
        dataWriter.append(arrData)
        labelWriter.append(arrLabel)
    dataWriter.close()
    labelWriter.close()
    print(count)




